use std::time::Duration;

use clap::Parser;
use serde::{Deserialize, Serialize};
use wtask_app::TimerApp;
use wtask_base::{error::WResult, export::{Local, Timelike, tokio_sleep}, logs::log_init, machine::{CMDMachineArgs, runtime_init}, timer::TimerRun};
use wtask_machine::{machine_args_to_proxy_and_local, server};



#[derive(Debug, Clone, Parser, Serialize, Deserialize)]
#[command(author, version, about="wTask服务端", help_template = "\
{before-help}
{about-with-newline}
{usage-heading} {usage}
{all-args}{after-help}

Version: {version}
Author: {author-with-newline}
")]
struct CMDArgs {
    #[command(flatten)]
    data: CMDMachineArgs,
}


fn main() -> WResult<()> {
    let args = CMDArgs::parse().data;
    log_init(&args.log_args);
    let runtime  = runtime_init(8)?;
    runtime.spawn(async {
        loop {
            // 保证从0秒左右开始运行任务
            let sec_gap = 60 - Local::now().second();
            tokio_sleep(Duration::from_secs(sec_gap as u64)).await;
            let _ = TimerRun::<TimerApp>::run_all().await;
        }
    });
    runtime.block_on(async move {
        let (config_local, config_proxy) = machine_args_to_proxy_and_local(args).unwrap();
        server(config_proxy, config_local).await.unwrap();
    });
    runtime.shutdown_background();
    Ok(())
}